<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
</head>
<body>
<form action="">
    <textarea name="message" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="发送消息" onclick="sendMsg(this.form.message.value)">
    <textarea id="responseText" style="height: 300px; width: 300px;"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value = ''">
</form>
<script>
    //服务器消息显示框
    var responseText = document.getElementById("responseText");
    var socket = null;
    //判断当前浏览器是否支持WebSocket
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:9999/hello");
        //相当于服务器端的MyTextWebSocketFrameHandler处理器类的channelRead0()方法
        //event中包含服务器端回送的消息
        socket.onmessage = function (event) {
            responseText.value += "\n" + event.data;
        };

        //连接开启的时候调用的方法
        socket.onopen = function (event) {
            responseText.value = "连接开启了";
        };

        //连接关闭的时候调用的的方法
        socket.onclose = function (event) {
            responseText.value += "\n" + "连接关闭了";
        };
    } else {
        alert("当前浏览器不支持WebSocket");
    }

    //发送消息到服务器
    function sendMsg(msg) {
        if (!socket) {  //先判断socket是否创建好了
            alert("当前浏览器不支持WebSocket");
            return;
        }
        //判断socket的状态是否处于打开的状态
        if (socket.readyState == WebSocket.OPEN) {
            //待发送的数据是否不为空
            if (msg.length > 0) {
                //通过Socket发送消息
                socket.send(msg);
            } else {
                alert("待发送的数据不能为空!");
            }
        } else {
            alert("连接未开启");
        }
    }
</script>
</body>
</html>